<?php
defined('DS') or define( 'DS' , DIRECTORY_SEPARATOR);
$cacheFile = dirname(__FILE__).DS.'..'.DS.'..'.DS.'..'.DS.'cache'.DS.'news'.DS.'newsThumbShell.php';
$notActiveFile =  dirname(__FILE__).DS.'..'.DS.'..'.DS.'..'.DS.'cache'.DS.'news'.DS.'notActiveFile.php';
if(is_file($cacheFile)){
	$data = include_once($cacheFile);
	$notActiveData = include_once($notActiveFile);
}else{
	exit;
}
//if it has not photo,then exit;
if(empty($data)) exit;

//load CRUB ENV
$config = include_once(dirname(__FILE__).DS.'..'.DS.'config.php');
$app=Yii::createConsoleApplication($config);
$app->commandRunner->addCommands(YII_PATH.'/cli/commands');
$env=@getenv('YII_CONSOLE_COMMANDS');
if(!empty($env))
	$app->commandRunner->addCommands($env);
$connection = Yii::app()->db;


//only grab one photo
end($data);
$photo = each($data);
//是否为空数据
if(!$photo['value']){
	$file_content = "<?php return ";
	reset($data);
	array_pop($data);
	$file_content .= var_export($data,true).';';
	safe_file_put_contents($cacheFile, $file_content);
	exit;

}
$config2 = 'config.php';
include_once('core.php');
SC::createApplication($config2);
$photoPath = '';
try {
	$webthumb = new Thumb();
	$webthumb->addUrl($photo['value'],'medium','140','100');
	$webthumb->submitRequests();
	$photoPath = $webthumb->getPhotoPath();
} catch (Exception $e) {
	switch($e->getCode()){
		case '700': //用Iecapt抓不到图片的处理
			$file_content = "<?php return ";
			reset($data);
			array_pop($data);
			$file_content .= var_export($data,true).';';
			safe_file_put_contents($cacheFile, $file_content);
			
			//记录不可访问的地址
			$file_content_not_active = "<?php return ";
			$notActiveData[$photo['key']] = $photo['value'];
			$file_content_not_active .= var_export($notActiveData,true).';';
			safe_file_put_contents($notActiveFile, $file_content_not_active);
			exit;
			break;
		default:
			print_r($e->getMessage());
	}
}
if($photoPath){
	$photoPath = '/' . str_replace('\\','/',$photoPath);
	//insert into database
	$sql = "update nc_news set `news_thumb` = '$photoPath' where `news_id` = ".$photo['key'];
	$connection->createCommand($sql)->execute();
	//delete cache from $cacheFile;

	$file_content = "<?php return ";
	reset($data);
	array_pop($data);
	$file_content .= var_export($data,true).';';
	safe_file_put_contents($cacheFile, $file_content);

}
function safe_file_put_contents($filename, & $content) {
		$fp = fopen($filename, 'w+'); 
		if (!$fp)   return false;
		if (flock($fp, LOCK_EX))    fwrite($fp, $content); 
		flock($fp,LOCK_UN); 
		fclose($fp); 
		return true; 
	} 
//print_r($photoPath);exit;